package com.finger.orderservice.controller;

import com.finger.modelservice.model.order.OrderInfo;
import com.finger.modelservice.result.Result;
import com.finger.orderservice.service.OrderInfoService;
import com.finger.orderservice.service.PaymentInfoService;
import com.finger.orderservice.service.WeixinPayService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Log4j2
@RequestMapping("site/order/wxPay")
@RestController
public class WeixinPayController {

    @Autowired
    private WeixinPayService weixinPayService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    // 根据订单号生成微信支付二维码
    @PostMapping("auth/createNative/{orderId}")
    public Result createNative(@PathVariable String orderId){

        Map<String,Object> resultMap = weixinPayService.createNative(orderId);

        return Result.ok(resultMap);
    }

    @GetMapping("auth/queryPayStatus/{orderId}")
    public Result queryPayStatus(@PathVariable String orderId){
        Map map = weixinPayService.queryPayStatus(orderId);

        if(map == null){
            return Result.fail().message("支付出错");
        }

        if("SUCCESS".equals(map.get("trade_state"))){

            paymentInfoService.paySuccess(map);
            return Result.ok(map).message("支付成功");
        }

        return Result.ok().message("支付中");
    }

    @GetMapping("auth/cancelOrder/{orderId}")
    public Result cancelOrder(@PathVariable String orderId){

        boolean isRefund = weixinPayService.cancelOrder(orderId);

        return Result.ok(isRefund);

    }

}
